from functools import wraps
import jwt
from django.http import JsonResponse

from django_system.settings import SECRET_KEY
from user.models import User


def check_permission(role_list):
    def decorator(func):
        @wraps(func)
        def wrapped_view(request, *args, **kwargs):
            # 从token中获取用户角色
            token = request.META.get('HTTP_AUTHORIZATION', None).split(' ')[1]
            user = jwt.decode(token, SECRET_KEY, algorithms=['HS256']).get('user')
            if not user:
                return JsonResponse({'msg': 'Unauthorized'}, status=401)
            user_roles = [i.name for i in User.objects.filter(username=user).first().roles.all()]
            if not any(x in role_list for x in user_roles):
                return JsonResponse({'msg': '权限不足', 'code': 400}, status=401)
            return func(request, *args, **kwargs)

        return wrapped_view

    return decorator
